package com.example.webapp.controller;

import com.example.webapp.entity.Project;
import com.example.webapp.repository.ProjectRepository;
import com.example.webapp.repository.UserRepository;
import com.example.webapp.security.UserPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import com.example.webapp.entity.User;
import org.springframework.http.HttpStatus;

import java.util.List;

@RestController
@RequestMapping("/projects")
public class ProjectController {

    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private UserRepository userRepository;

    @GetMapping
    public ResponseEntity<?> getAllProjects(@AuthenticationPrincipal UserPrincipal currentUser) {
        try {
            if (currentUser == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User not authenticated");
            }

            User user = userRepository.findById(currentUser.getId())
                .orElseThrow(() -> new RuntimeException("User not found"));

            List<Project> projects = projectRepository.findAllByUserOrderByCreatedAtDesc(user);
            return ResponseEntity.ok(projects);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<Project> getProjectById(@PathVariable Long id) {
        return projectRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<?> createProject(@RequestBody Project project, @AuthenticationPrincipal UserPrincipal currentUser) {
        try {
            if (projectRepository.existsByName(project.getName())) {
                return ResponseEntity.badRequest().body("项目名称已存在");
            }
            
            // 设置项目所有者
            User user = userRepository.findById(currentUser.getId())
                .orElseThrow(() -> new RuntimeException("User not found"));
            project.setUser(user);
            
            return ResponseEntity.ok(projectRepository.save(project));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateProject(@PathVariable Long id, @RequestBody Project project) {
        return projectRepository.findById(id)
                .map(existingProject -> {
                    // 如果名称已更改，检查新名称是否已存在
                    if (!existingProject.getName().equals(project.getName()) &&
                            projectRepository.existsByName(project.getName())) {
                        return ResponseEntity.badRequest().body("项目名称已存在");
                    }
                    
                    existingProject.setName(project.getName());
                    existingProject.setDescription(project.getDescription());
                    return ResponseEntity.ok(projectRepository.save(existingProject));
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteProject(@PathVariable Long id) {
        return projectRepository.findById(id)
                .map(project -> {
                    projectRepository.delete(project);
                    return ResponseEntity.ok().build();
                })
                .orElse(ResponseEntity.notFound().build());
    }
} 